package unei;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Created by sunlei on 2015/6/30.
 */
public class PhaserDemo {

    private static Phaser phaser=new Phaser(5);

    /**
     * Phaser 作为CountDownLatch使用
     */
    public static void asCountDownLatch(){
        Random rand=new Random();
        for(int i=0;i<5;i++){
            CDLRunnable cdlRunnable=new CDLRunnable(rand.nextInt(10));
            new Thread(cdlRunnable).start();
        }
    }

    static class CDLRunnable implements  Runnable{

        private int sleep;

        public CDLRunnable(int sleep){
            this.sleep=sleep;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(sleep);
                phaser.arriveAndAwaitAdvance();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        asCountDownLatch();
    }
}
